package com.zh.springcloud.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @Description: 全局自定义日志过滤器
 * @ClassName MyLogGlobalFilter
 * @date: 2021.07.12 14:45
 * @Author: zhanghang
 */
@Component
public class MyLogGlobalFilter implements GlobalFilter, Ordered {
	/**
	 * description: 自定义过滤条件
	 * 例如：我们这个过滤器指定访问参数必须带有 uname 参数，否则不允许访问
	 */
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		System.out.println("***********come in MyLogGlobalFilter: "+ new Date());
		String uname = exchange.getRequest().getQueryParams().getFirst("uname");
		if (null == uname){
			System.out.println("*********用户名为null,非法用户****");
			exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
			return exchange.getResponse().setComplete();
		}
		// 将exchange 传入到下一个过滤器
		return chain.filter(exchange);
	}

	/**
	 * description: 设置加载过滤器的顺序，数值越小，优先级越高
	 * date: 2021年-07月-12日 14:47
	 * author: zhanghang
	 * 
	 * @param 
	 * @return int
	 */ 
	@Override
	public int getOrder() {
		return 0;
	}
}
